<?php


namespace App\Services;


use App\Models\Folder;
use App\Models\FolderLabel;
use App\Models\Papper;
use App\Utils\Code;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Validator;

class FolderService extends BaseService
{
    /**
     * 创建数据
     * @param array $params
     * @return \Illuminate\Database\Eloquent\Builder|\Illuminate\Database\Eloquent\Model|object|null
     * @throws \Exception
     */
    public function store(array $params) {
        if (!$this->checkParams($params)){
            throw new \Exception('请求参数验证不通过', Code::PARAMETER_ERROR);
        }
        return DB::transaction(function () use ($params){
            $model = new Folder();
            if (Folder::where('name', $params['name'])->first()) {
                throw new \Exception('名称已经存在', Code::EXIST_REPEAT);
            }
            $model->name = $params['name'];
            $model->user_id = $this::$userId;
            if (isset($params['speed']) && is_numeric($params['speed'])){
                $model->speed = $params['speed'];
            }
            if (isset($params['label_id']) && is_numeric($params['label_id'])){
                $model->label_id = $params['label_id'];
            }
            $model->save();
            return $this->show($model->id);
        });
    }

    /**
     * 数据信息
     * @param $id
     * @param bool $simple
     * @param bool $abnormal
     * @return \Illuminate\Database\Eloquent\Builder|\Illuminate\Database\Eloquent\Model|object|null
     * @throws \Exception
     */
    public function show($id, $abnormal = true) {
        $model = Folder::where('id', $id)->first();
        if (!$model && $abnormal){
            throw new \Exception('不存在的ID', Code::EMPTY_DATA);
        }
        return $model;
    }

    /**
     * 更新数据
     * @param $id
     * @param array $params
     * @return \Illuminate\Database\Eloquent\Builder|\Illuminate\Database\Eloquent\Model|object|null
     * @throws \Exception
     */
    public function update($id, array $params) {
        if (!$this->checkParams($params, true)){
            throw new \Exception('请求参数验证不通过', Code::PARAMETER_ERROR);
        }
        return DB::transaction(function () use ($id, $params){
            $model = $this->show($id);
            if (Folder::where('name', $params['name'])->where('id', '<>', $id)->first()) {
                throw new \Exception('名称已经存在', Code::EXIST_REPEAT);
            }
            $model->name = $params['name'];
            if (isset($params['speed']) && is_numeric($params['speed'])){
                $model->speed = $params['speed'];
            }
            if (key_exists('label_id', $params)){
                $model->label_id = $params['label_id'];
            }
            $model->save();
            return $this->show($id);
        });
    }

    /**
     * 删除数据
     * @param $id
     * @return mixed
     * @throws \Exception
     */
    public function destroy(array $ids = []) {
        if (!$this::$admin) {
            throw new \Exception('你没有权限进行删除', Code::LACK_OF_CONDITIONS);
        }
        if (Papper::whereIn('folder_id', $ids)->exists()) {
            throw new \Exception('文件夹存在文案，无法删除', Code::LACK_OF_CONDITIONS);
        }
        return DB::transaction(function () use ($ids) {
            return Folder::whereIn('id', $ids)->delete();
        });
    }

    /**
     * 数据分页
     * @param array $params
     * @return \Illuminate\Contracts\Pagination\LengthAwarePaginator
     */
    public function lists(array $params = []) {
        if (isset($params['mode']) && $params['mode'] == 'select') {
            $model = Folder::select(['id', 'name']);
            if (isset($params['label_id']) && $params['label_id']) {
                $model = $model->where('label_id', '=', $params['label_id']);
            }
            $lists = $model->orderBy('id', 'desc')->get();
            return $lists;
        } else {
            $model = Folder::with(['label', 'user']);
        }
        if (isset($params['label_id']) && $params['label_id']) {
            $model = $model->where('label_id', '=', $params['label_id']);
        }
        if (isset($params['name']) && $params['name']) {
            $model = $model->where('name', 'like', '%'.$params['name'].'%');
        }
        $lists = $model->orderBy('id', 'desc')->paginate(isset($params['per_page']) ? (int)$params['per_page'] : 15);
        return $lists;
    }

    /**
     * 验证参数
     * @param array $params
     * @param bool $isUpdate
     * @return array
     * @throws \Exception
     */
    private function checkParams(array $params, $isUpdate = false){
        $rules = [
            'name' => ['bail', 'required', 'string', 'between:1,50'],
            'speed' => ['bail', 'nullable', 'numeric'],
        ];
        if ($isUpdate){
            // 删除必选条件
            foreach ($rules as $field => &$rule){
                if (isset($rule[1]) && $rule[1] == 'required') {
                    unset($rule[1]);
                }
            }
        }
        $validator = Validator::make($params, $rules, [], [
            'name' => '名称',
            'speed' => '语速设置'
        ]);
        if ($validator->fails()) {
            throw new \Exception($validator->errors()->first(), Code::PARAMETER_ERROR);
        }
        return $params;
    }
    
    /**
     * 创建数据
     * @param array $params
     * @return \Illuminate\Database\Eloquent\Builder|\Illuminate\Database\Eloquent\Model|object|null
     * @throws \Exception
     */
    public function storeLabel(array $params) {
        if (empty($params['name'])){
            throw new \Exception('名称不能为空', Code::PARAMETER_ERROR);
        }
        if (FolderLabel::where('name', $params['name'])->exists()) {
            throw new \Exception('名称已经存在', Code::EXIST_REPEAT);
        }
        return DB::transaction(function () use ($params){
            $model = new FolderLabel();
            $model->name = $params['name'];
            $model->save();
            return $model;
        });
    }

    /**
     * 更新数据
     * @param $id
     * @param array $params
     * @return \Illuminate\Database\Eloquent\Builder|\Illuminate\Database\Eloquent\Model|object|null
     * @throws \Exception
     */
    public function updateLabel($id, array $params) {
        if (empty($params['name'])){
            throw new \Exception('名称不能为空', Code::PARAMETER_ERROR);
        }
        if (FolderLabel::where('name', $params['name'])->where('id', '<>', $id)->first()) {
            throw new \Exception('名称已经存在', Code::EXIST_REPEAT);
        }
        return DB::transaction(function () use ($id, $params){
            $model = FolderLabel::find($id);
            $model->name = $params['name'];
            $model->save();
            return $model;
        });
    }

    /**
     * 删除数据
     * @param $id
     * @return mixed
     * @throws \Exception
     */
    public function destroyLabel(array $ids = []) {
        if (!$this::$admin) {
            throw new \Exception('你没有权限进行删除', Code::LACK_OF_CONDITIONS);
        }
        return DB::transaction(function () use ($ids) {
            return FolderLabel::whereIn('id', $ids)->delete();
        });
    }

    public function listsLabel() {
        $model = FolderLabel::select(['id', 'name']);
        $lists = $model->orderBy('id', 'desc')->get();
        return $lists;
    }
}
